#version 300 es
precision mediump float;

in vec2 v_texCoord;
in vec4 v_color;

uniform sampler2D u_sceneTexture;    // 原始场景纹理
uniform sampler2D u_ambientTexture;  // 环境光纹理
uniform sampler2D u_lightTexture;    // 点光源纹理
uniform float u_lightIntensity;      // 点光源强度控制
uniform float u_lightIntensityCompressVal;//光源强度数据压缩

out vec4 fragColor;

void main() {
    // 采样三个纹理
    vec4 sceneColor = texture(u_sceneTexture, v_texCoord) * v_color;
    vec4 ambientColor = texture(u_ambientTexture, v_texCoord);
    vec4 lightColor = texture(u_lightTexture, v_texCoord);

    // 跳过透明像素
    if (sceneColor.a <= 0.0) {
        fragColor = sceneColor;
        return;
    }

    //    // 环境光影响（乘法混合）
    //    vec3 pass1Color = sceneColor.rgb * ambientColor.rgb;
    //
    //    // 点光源影响
    //    float finalLightIntensity = length(lightColor.rgb) * u_lightIntensity;
    //
    //    // 混合环境光与点光源
    //    vec3 finalColor;
    //    if(finalLightIntensity > 0.0){
    //        vec3 lightenedColor = sceneColor.rgb * finalLightIntensity; // 增益原材质
    //        finalColor = pass1Color + lightenedColor; // 覆盖效果
    //    } else
    //        finalColor = pass1Color;


    vec3 finalColor = vec3(0.0);

    //计算环境光
    vec3 c = ambientColor.rgb;
    float ambientColorLength = 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;
    float sceneColorIntensity = max(1.0, ambientColorLength * 1.2);
    vec3 pass1Color = sceneColor.rgb * sceneColorIntensity * ambientColor.rgb;

    //计算点光源
    float finalLightIntensity = lightColor.a;
    finalLightIntensity *= u_lightIntensity;

    //混合环境光与点光源
    if (finalLightIntensity > 0.0) {
        vec3 lightenedColor = sceneColor.rgb * lightColor.rgb * finalLightIntensity * 0.05;//增益原材质
        pass1Color = mix(pass1Color, sceneColor.rgb, lightColor.a);
        vec3 pass2Color = pass1Color + lightenedColor;//覆盖

        finalColor = pass2Color;
    }
    else
        finalColor = pass1Color;

    //最终颜色
    fragColor = vec4(finalColor, sceneColor.a);
}
